<template>
  <div class="rent-room-detail">
    <!-- 导航栏 -->
    <div class="nav-bar">
      <div class="nav-content">
        <el-icon class="back-icon" @click="goBack">
          <ArrowLeft />
        </el-icon>
        <span class="nav-title">房源详情</span>
        <div class="nav-placeholder"></div>
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="detail-content" v-loading="loading">
      <div v-if="roomDetail" class="room-detail-container">
        <!-- 房源图片轮播 -->
        <div class="room-images">
          <el-carousel :interval="4000" arrow="hover" height="250px">
            <el-carousel-item v-for="(image, index) in roomImages" :key="index">
              <img :src="image" :alt="`房源图片${index + 1}`" class="room-image" />
            </el-carousel-item>
          </el-carousel>
      </div>

        <!-- 房源基本信息 -->
        <div class="room-info-card">
          <div class="room-title-section">
            <h2 class="room-title">{{ roomDetail.houseTitle }}</h2>
            <div class="room-tags" v-if="roomDetail.tags">
              <span v-for="tag in roomDetail.tags" :key="tag.name" class="room-tag">
                {{ tag.name }}
              </span>
            </div>
      </div>

          <div class="room-basic-info">
            <p class="room-address">{{ roomDetail.address }}</p>
            <div class="room-details">
              <span class="room-area">{{ roomDetail.rentArea }}㎡</span>
              <span class="separator">|</span>
              <span class="room-direction">南北</span>
              <span class="separator">|</span>
              <span class="room-decoration">精装</span>
          </div>
        </div>

          <div class="price-section">
            <div class="price-info">
              <span class="price">¥{{ roomDetail.rentPriceListing }}</span>
              <span class="price-unit">/{{ roomDetail.rentPriceUnit }}</span>
            </div>
        </div>
      </div>

        <!-- 距离信息 -->
        <div class="distance-card" v-if="roomDetail.distanceInfo">
          <div class="distance-info">
            <el-icon class="location-icon">
              <Location />
            </el-icon>
            <span class="distance-text">{{ roomDetail.distanceInfo }}</span>
          </div>
      </div>

        <!-- 房源描述 -->
        <div class="description-card">
          <h3 class="card-title">房源描述</h3>
          <p class="description-text">
            {{ roomDetail.description || '这是一套精装修的房源，设施齐全，交通便利，适合长期居住。房间采光良好，周边配套设施完善，是您理想的居住选择。' }}
          </p>
          </div>
          </div>

      <!-- 空数据状态 -->
      <div v-else-if="!loading" class="empty-state">
        <div class="empty-content">
          <img src="@/assets/imgs/blank.png" alt="房源不存在" class="empty-image" />
          <h3 class="empty-title">房源信息不存在</h3>
          <p class="empty-description">该房源可能已下架或不存在</p>
          <el-button type="primary" @click="goBack">返回</el-button>
          </div>
        </div>
      </div>

    <!-- 底部预约按钮 -->
    <div class="bottom-actions" v-if="roomDetail">
      <div class="action-buttons">
        <el-button class="contact-btn" @click="handleContact">
          <el-icon><Phone /></el-icon>
          联系房东
        </el-button>
        <el-button type="primary" class="book-btn" @click="showBookingModal">
          预约看房
        </el-button>
        </div>
      </div>

    <!-- 预约看房弹窗 -->
    <el-dialog
      v-model="bookingModalVisible"
      title="预约看房"
      width="90%"
      :before-close="handleCloseBooking"
      class="booking-dialog"
    >
      <div class="booking-form">
        <div class="form-item">
          <label class="form-label">姓名</label>
          <el-input 
            v-model="bookingForm.name" 
            placeholder="请输入姓名"
            clearable
          />
        </div>
        
        <div class="form-item">
          <label class="form-label">手机号</label>
          <el-input 
            v-model="bookingForm.phone" 
            placeholder="请输入手机号"
            clearable
            maxlength="11"
          />
            </div>
        
        <div class="form-item">
          <label class="form-label">预约日期</label>
          <div class="date-grid">
            <div 
              v-for="(date, index) in dateList" 
              :key="date.date"
              class="date-item"
              :class="{ active: selectedDateIndex === index }"
              @click="selectDate(index)"
            >
              <div class="date-day">{{ date.day }}</div>
              <div class="date-week">{{ date.week }}</div>
          </div>
        </div>
      </div>

        <div class="form-item">
          <label class="form-label">备注信息</label>
          <el-input 
            v-model="bookingForm.comment" 
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
            clearable
          />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="bookingModalVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBooking" :loading="submitting">
            确认预约
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Location, Phone } from '@element-plus/icons-vue'
import { getRoomDetailApi } from '@/api/room'
import { bookRentRoomApi } from '@/api/booking'

    const router = useRouter()
    const route = useRoute()
    
// 页面状态
const loading = ref(false)
const submitting = ref(false)
const bookingModalVisible = ref(false)
const roomDetail = ref(null)
const selectedDateIndex = ref(0)

// 预约表单
const bookingForm = reactive({
  name: '',
  phone: '',
  date: '',
  comment: '',
  houseId: ''
})

// 生成未来7天的日期列表
const generateDateList = () => {
  const dates = []
  const today = new Date()
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(today)
    date.setDate(today.getDate() + i)
    
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const week = i === 0 ? '今天' : weekDays[date.getDay()]
    
    dates.push({
      date: `${date.getFullYear()}-${month}-${day}`,
      day: day,
      week: week
    })
  }
  
  return dates
}

const dateList = ref(generateDateList())

// 房源图片列表
const roomImages = computed(() => {
  if (!roomDetail.value) return []
  return [
    roomDetail.value.housePicture,
    '/src/assets/imgs/room_text_bg.png',
    '/src/assets/imgs/service_bg.png'
  ]
})

// 获取房源详情
const getRoomDetail = async () => {
  try {
    loading.value = true
    const roomId = route.params.id
    
    // 调用房源详情API
    const roomDetailData = await getRoomDetailApi(roomId)
    
    roomDetail.value = roomDetailData.data
    //console.log(roomDetail.value)
    bookingForm.houseId = roomId
    
    // 设置默认预约日期
    if (dateList.value.length > 0) {
      bookingForm.date = dateList.value[0].date
    }
    
    console.log('房源详情:', roomDetailData)
  } catch (error) {
    console.error('获取房源详情失败:', error)
    ElMessage.error('获取房源详情失败')
  } finally {
    loading.value = false
  }
}

// 选择预约日期
const selectDate = (index) => {
  selectedDateIndex.value = index
  bookingForm.date = dateList.value[index].date
}

// 显示预约弹窗
const showBookingModal = () => {
  bookingModalVisible.value = true
}

// 关闭预约弹窗
const handleCloseBooking = () => {
  bookingModalVisible.value = false
}

// 提交预约
const submitBooking = async () => {
  try {
    // 表单验证
    if (!bookingForm.name.trim()) {
      ElMessage.warning('请输入姓名')
      return
    }
    
    if (!bookingForm.phone.trim()) {
      ElMessage.warning('请输入手机号')
      return
    }
    
    // 简单的手机号验证
    const phoneReg = /^1[3-9]\d{9}$/
    if (!phoneReg.test(bookingForm.phone)) {
      ElMessage.warning('请输入正确的手机号')
      return
    }
    
    submitting.value = true
    
    // 保存提交的数据
    const submitData = {
      name: bookingForm.name,
      phone: bookingForm.phone,
      date: bookingForm.date,
      comment: bookingForm.comment || '无备注',
      houseId: bookingForm.houseId
    }
    
    // 提交预约
    const result = await bookRentRoomApi(submitData)
    
    console.log('API响应结果:', result)
    console.log('响应类型:', typeof result)
    console.log('响应详情:', JSON.stringify(result, null, 2))
    
    // 简化判断逻辑，只要API调用没有抛出异常，就认为预约成功
    // 因为bookRentRoomApi如果失败会直接抛出异常，能到这里说明请求成功了
    ElMessage.success('预约成功！')
    bookingModalVisible.value = false
    
    // 触发全局事件，通知订单管理页面刷新（在重置表单前）
    window.dispatchEvent(new CustomEvent('booking-success', {
      detail: {
        roomId: submitData.houseId,
        roomInfo: roomDetail.value,
        bookingInfo: submitData
      }
    }))
    
    // 重置表单
    bookingForm.name = ''
    bookingForm.phone = ''
    bookingForm.comment = ''
    selectedDateIndex.value = 0
    bookingForm.date = dateList.value[0].date
    
      } catch (error) {
    console.error('预约失败:', error)
    ElMessage.error(error.message || '预约失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 联系房东
const handleContact = () => {
  ElMessage.info('正在为您转接房东电话...')
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 页面初始化
    onMounted(() => {
  getRoomDetail()
})
</script>

<style scoped>
.rent-room-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  height: 44px;
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
  color: #333;
  transition: color 0.3s ease;
}

.back-icon:hover {
  color: #409eff;
}

.nav-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.nav-placeholder {
  width: 20px;
}

.detail-content {
  flex: 1;
  padding-bottom: 80px;
}

.room-detail-container {
  background-color: #fff;
}

.room-images {
  position: relative;
}

.room-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.room-info-card {
  padding: 20px;
  background-color: #fff;
  border-bottom: 8px solid #f5f5f5;
}

.room-title-section {
  margin-bottom: 12px;
}

.room-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.room-tags {
  display: flex;
  gap: 6px;
}

.room-tag {
  background-color: #409eff;
  color: #fff;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.room-basic-info {
  margin-bottom: 16px;
}

.room-address {
  font-size: 14px;
  color: #666;
  margin: 0 0 8px 0;
}

.room-details {
  font-size: 13px;
  color: #999;
}

.separator {
  margin: 0 8px;
}

.price-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-info {
  display: flex;
  align-items: baseline;
}

.price {
  font-size: 24px;
  font-weight: 600;
  color: #e74c3c;
}

.price-unit {
  font-size: 14px;
  color: #999;
  margin-left: 4px;
}

.distance-card {
  padding: 16px 20px;
  background-color: #fff;
  border-bottom: 8px solid #f5f5f5;
}

.distance-info {
  display: flex;
  align-items: center;
}

.location-icon {
  font-size: 16px;
  color: #409eff;
  margin-right: 8px;
}

.distance-text {
  font-size: 14px;
  color: #666;
}

.description-card {
  padding: 20px;
  background-color: #fff;
  border-bottom: 8px solid #f5f5f5;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.description-text {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  padding: 40px 20px;
}

.empty-content {
  text-align: center;
}

.empty-image {
  width: 120px;
  height: 120px;
  opacity: 0.6;
  margin-bottom: 20px;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.empty-description {
  font-size: 14px;
  color: #666;
  margin: 0 0 20px 0;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1px solid #e0e0e0;
  padding: 12px 16px;
  z-index: 100;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.contact-btn {
  flex: 1;
  height: 44px;
  border: 1px solid #409eff;
  color: #409eff;
}

.book-btn {
  flex: 2;
  height: 44px;
}

/* 预约弹窗样式 */
.booking-form {
  padding: 20px 0;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.date-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8px;
}

.date-item {
  text-align: center;
  padding: 8px 4px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.date-item:hover {
  border-color: #409eff;
  background-color: #f0f8ff;
}

.date-item.active {
  border-color: #409eff;
  background-color: #409eff;
  color: #fff;
}

.date-day {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 2px;
}

.date-week {
  font-size: 12px;
  opacity: 0.8;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-content {
    padding: 8px 12px;
  }
  
  .nav-title {
    font-size: 16px;
  }
  
  .room-info-card {
    padding: 16px;
  }
  
  .room-title {
    font-size: 18px;
  }
  
  .price {
    font-size: 20px;
  }
  
  .distance-card,
  .description-card {
    padding: 16px;
  }
  
  .bottom-actions {
    padding: 10px 12px;
  }
  
  .action-buttons .el-button {
  height: 40px;
}

  .date-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

/* Element Plus 组件样式覆盖 */
:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 0;
}

:deep(.el-dialog__body) {
  padding: 0 20px;
}

:deep(.el-dialog__footer) {
  padding: 0 20px 20px;
}

:deep(.el-carousel__indicator--horizontal .el-carousel__button) {
  background-color: rgba(255, 255, 255, 0.6);
}

:deep(.el-carousel__indicator--horizontal.is-active .el-carousel__button) {
  background-color: #409eff;
}

/* Loading状态样式 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
}
</style>